package team.epos.merchant.filter;

import org.apache.commons.lang3.StringUtils;
import team.epos.utils.pojo.MUser;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author CHENKI
 */
public class LoginFilter implements Filter {

    private Set<String> ignoreSet = new HashSet<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String[] ignore = filterConfig.getInitParameter("ignore").split(",");
        ignoreSet.addAll(Arrays.asList(ignore));
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpSession session = httpRequest.getSession();
        MUser user = (MUser) session.getAttribute("muser");
//      截取当前文件名用于比较
        String currentURL = httpRequest.getRequestURI();

        if (verifyIgnore(currentURL)) {
            chain.doFilter(request, response);
        } else {
            //判断如果没有取到用户信息,就跳转到登陆页面
            if (user == null || "".equals(user)) {
                //跳转到登陆页面;
                ((HttpServletResponse) response).sendRedirect("/html/login.html");
            } else {
                //已经登陆,继续此次请求
                chain.doFilter(request, response);
            }
        }
    }

    @Override
    public void destroy() {
        ignoreSet = null;
    }

    private boolean verifyIgnore(String url) {
        for (String s : ignoreSet) {
            if (url.contains(s)) {
                return true;
            }
        }
        return false;
    }
}
